package com.xing.http;

import com.xing.tools.MagnetSearchUtil;
import com.xing.vo.MatchConfig;
import com.xing.vo.SearchException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xingzhe on 2018/10/20.
 */
@Component
public class BaseSearchService {
    private static final Logger logger = LoggerFactory.getLogger(BaseSearchService.class);

    private MatchConfig matchConfig;

    @Autowired
    private HttpAPIService httpAPIService;

    public String getMagnetById(String id,MatchConfig matchConfig) {
        this.matchConfig = matchConfig;
        logger.warn("开始查找 website: " + matchConfig.getDomain());
        String magnet = "";
        try {
            //参数校验
            id = checkParam(id);
            //获取地址
            String url = matchConfig.getDomain() + matchConfig.getDomainTail().replace("{id}", id);
            String indexContent = httpAPIService.doGet(url);
            if(StringUtils.isEmpty(indexContent)){
                return magnet;
            }
            Document document = Jsoup.parse(indexContent);
            //数量判断
            int num = getSearchNum(document, matchConfig.getNumReg(), matchConfig.getNumUnit());
            logger.warn("查找到"+num+"条记录");
            //获取list
            List<String> detailUrls = getDetailUrls(document, id);
            //获取链接
            magnet = getMagnet(detailUrls);
        }catch (SearchException e){
            logger.error("检索词: {}\tmsg:{}\t{}",id,e.getMessage(),matchConfig.getDomain());
        }catch (Exception e){
            logger.error("exception! id:{},{}",id,matchConfig.getDomain(),e);
            e.printStackTrace();
        }
        return magnet;
    }

    private String getMagnet(List<String> detailUrls) throws Exception {
        if (CollectionUtils.isEmpty(detailUrls)) {
            throw new SearchException("detail url 列表是空",104);
        }
        for (String detailUrl : detailUrls) {
            String detailContent = httpAPIService.doGet(detailUrl);
            if (StringUtils.isEmpty(detailContent)) {
                continue;
            }
            Document document = Jsoup.parse(detailContent);
            //获取文件描述
            String detailDesc = getFirstText(document,matchConfig.getDetailDescReg());
            //过滤
            if (!MagnetSearchUtil.isDetailRight(detailDesc)) {
                continue;
            }
            //获取链接
            String magnet = getFirstHref(document,matchConfig.getDetailMagnetReg());
            if(!StringUtils.isEmpty(magnet)) {
                return magnet;
            }
        }
        return "";
    }

    private List<String> getDetailUrls(Element document,String id) throws SearchException {
        List<String> detailUrls = new ArrayList<>();
        Elements elements = document.select(matchConfig.getListReg());
        if (CollectionUtils.isEmpty(elements)) {
            throw new SearchException("未找到title list!",103);
        }
        for (Element element : elements) {
            String titleText = getFirstText(element,matchConfig.getListTitleReg());
            if (!MagnetSearchUtil.isTitleRight(titleText, id)) {
                continue;
            }

            String size = getTextByIndex(element,matchConfig.getListSizeReg().getReg(),matchConfig.getListSizeReg().getIndex());
            if (!size.contains("G")) {
                continue;
            }

            String detailUrl = getFirstHref(element,matchConfig.getListDetailUrlReg());
            if(detailUrl.indexOf("http") == 0){
                detailUrls.add(detailUrl);
            }else if(detailUrl.indexOf("/") == 0){
                detailUrls.add(matchConfig.getDomain() + detailUrl);
            }else{
                throw new SearchException("竟然url跳转开头是那个啥:"+detailUrl,105);
            }
        }
        return detailUrls;
    }

    private String getFirstHref(Element element, String reg){
        return getHrefByIndex(element,reg,0);
    }

    private String getHrefByIndex(Element element, String reg, int index){
        String result = element.select(reg).get(index).attr("href");
        return result;
    }

    private String getFirstText(Element element, String reg) {
        return getTextByIndex(element, reg, 0);
    }

    private String getTextByIndex(Element element, String reg, int index) {
        Elements elements = element.select(reg);
        if(elements.size() <= 0){
            return null;
        }
        String result = elements.get(index).text();
        return result;
    }

    private int getSearchNum(Element element,String reg, String unit) throws SearchException {
        String numText = getFirstText(element,reg);
        if(StringUtils.isEmpty(numText)){
            throw new SearchException("未找到记录",108);
        }
        numText = numText.substring(0, numText.indexOf(unit));
        int num = getNumFromText(numText);
        if (num <= 0) {
            throw new SearchException("num为0",102);
        }
        return num;
    }

    private String checkParam(String id) throws SearchException{
        if (StringUtils.isEmpty(id)) {
            throw new SearchException("参数检查失败",101);
        }
        id = id.toLowerCase();
        return id;
    }

    private int getNumFromText(String text) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(text);
        String sNum = m.replaceAll("").trim();
        return Integer.parseInt(sNum);
    }
}
